package org.locker.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.locker.common.core.domain.model.LoginUser;
import org.locker.common.core.enums.UserType;
import org.locker.common.satoken.utils.LoginHelper;
import org.locker.domain.User;
import org.locker.domain.vo.LoginWxVo;
import org.locker.service.IAuthStrategy;
import org.locker.service.IUserService;
import org.springframework.stereotype.Service;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("wx" + IAuthStrategy.BASE_NAME)
@AllArgsConstructor
public class WxAuthStrategy implements IAuthStrategy {

    public static final String MINI_APP = "miniapp";
    public static final Integer TIME_OUT = 604800;
    public static final Integer ACTIVE_TIMEOUT = 1800;
    public static final String CLIENT_ID = "428a8310cd442757ae699df5d894f8888";
    private final IUserService userService;



    @Override
    public LoginWxVo loginByOpenId(String openId) {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenId, openId));
        if (ObjectUtil.isNull(user)) {
            //用户不存在，直接注册一条
            user = new User();
            user.setOpenId(openId);
            userService.save(user);
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        SaLoginModel model = new SaLoginModel();
        model.setDevice(MINI_APP);
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
//        model.setTimeout(TIME_OUT);
//        model.setActiveTimeout(ACTIVE_TIMEOUT);
        model.setExtra(LoginHelper.CLIENT_KEY, CLIENT_ID);
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginWxVo loginWxVo = new LoginWxVo();
        loginWxVo.setAccessToken(StpUtil.getTokenValue());
        loginWxVo.setExpireIn(StpUtil.getTokenTimeout());
        loginWxVo.setClientId(CLIENT_ID);
        return loginWxVo;
    }

    public LoginUser buildLoginUser(User user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getRealName());
        loginUser.setNickname(user.getNickname());
        loginUser.setUserType(UserType.WX_USER.getUserType());
        return loginUser;
    }

}
